package com.lagou.demo.filter;

import com.lagou.demo.feign.TokenFeignServiceI;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

@Slf4j
@Component
public class RequestFilter implements GlobalFilter, Ordered {

    @Autowired
    private TokenFeignServiceI tokenService ;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 若没有权限, 则跳转至登录页面
        URI uri = request.getURI();
        if (uri.getPath().contains("/api/user/") || uri.getPath().contains("/api/code/")) {
            // ⽤用户微服务和验证码微服务的请求不不过滤（⽹网关调⽤用下游
            //⽤用户微服务的token验证接⼝口）
//            进⾏行行IP注册接⼝口的防暴暴刷控制，
            if (uri.getPath().contains("/api/user/register")) {
                // todo 错误码： 303，错误信息：您频繁进⾏注册，请求已被拒绝）
            }

        } else {
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            List<HttpCookie> token = cookies.get("token");

            boolean valid = token == null ? false : tokenService.checkToken(token.get(0).getValue());
            if (!valid) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
                log.debug("=====> 该请求token不合法, token 为:{}", token);
                String data = "Request be denied!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
